<template>
  <ul class="app-header-nav">
    <li class="home" :class="{ active: $route.path === '/' }">
      <RouterLink to="/">首页</RouterLink>
    </li>
    <li
      v-for="item in $store.state.category.list"
      :key="item.id"
      @mouseenter="bol = true"
      :class="{ active: newId === item.id }"
    >
      <router-link @click="bol = false" :to="'/category/' + item.id">{{
        item.name
      }}</router-link>
      <!-- 二级菜单 -->
      <div class="layer" v-show="bol">
        <ul>
          <li v-for="i in item.children" :key="i.id">
            <router-link @click="bol = false" :to="'/category/sub/' + i.id">
              <img :src="i.picture" alt="" />
              <p>{{ i.name }}</p>
            </router-link>
          </li>
        </ul>
      </div>
    </li>
  </ul>
</template>

<script>
import { ref, computed } from 'vue'
import { useRoute } from 'vue-router'
import { useStore } from 'vuex'
export default {
  name: 'AppHeaderNav',
  setup () {
    const bol = ref(true)
    const route = useRoute()
    const store = useStore()
    // 需要借助路由上的id匹配一个一级类目的id(依赖一个或者多个值产生一个新的值)
    const newId = computed(() => {
      // route有大小写之说的
      if (route.path.toLowerCase().startsWith('/category/sub/')) {
        // 二级类目路由处理
        let _id = ''
        store.state.category.list.forEach(item => {
          item.children &&
            item.children.forEach(item2 => {
              if (item2.id === route.params.id) {
                _id = item.id
              }
            })
        })
        return _id
      } else {
        // 一级类目路由处理
        return route.params.id
      }
    })

    return { bol, newId }
  }
}
</script>

<style scoped lang="less">
.app-header-nav {
  width: 820px;
  display: flex;
  justify-content: space-around;
  padding-left: 40px;
  position: relative;
  z-index: 998;
  > li {
    margin-right: 40px;
    width: 38px;
    text-align: center;
    > a {
      font-size: 16px;
      line-height: 32px;
      height: 32px;
      display: inline-block;
    }
    &.active {
      > a {
        color: @xtxColor;
        border-bottom: 1px solid @xtxColor;
      }
    }
    &:hover {
      > a {
        color: @xtxColor;
        border-bottom: 1px solid @xtxColor;
      }
      > .layer {
        height: 132px;
        opacity: 1;
      }
    }
  }
}
.layer {
  width: 1240px;
  background-color: #fff;
  position: absolute;
  left: -200px;
  top: 56px;
  height: 0;
  overflow: hidden;
  opacity: 0;
  box-shadow: 0 0 5px #ccc;
  transition: all 0.2s 0.1s;
  ul {
    display: flex;
    flex-wrap: wrap;
    padding: 0 70px;
    align-items: center;
    height: 132px;
    li {
      width: 110px;
      text-align: center;
      img {
        width: 60px;
        height: 60px;
      }
      p {
        padding-top: 10px;
      }
      &:hover {
        p {
          color: @xtxColor;
        }
      }
    }
  }
}
</style>
